﻿Ext.define('app.prm.inquiry.Create', {
    extend: 'Ext.window.Window',
    inquiryId: 0,
    subId: 0,
    autoScroll: true,
    modal: true,
    width: 850,
    height: 600,
    referenceHolder: true,
    controller: 'inquiry',
    requires: ['app.prm.inquiry.InquiryController', 'app.prm.inquiry.ViewModel'],
    viewModel: {
        type: 'inquiryModel'
    },
    buttonAlign: 'center',
    initComponent: function () {
        var me = this;
        me.items = [
            me.getChemInfo(),
            me.getProInfo(),
            me.getBackInfo()
        ];
        me.buttons = [
            { text: '保存', handler: me.Submit, scope: this },

            { text: '重新技术评估', handler: me.BtnReTA, bind: { hidden: "{hideBtnReTA}" }, scope: this },
            { text: '待客户确认', handler: me.BtnPending, bind: { hidden: "{hideBtnPending}" }, scope: this },
            { text: '结束', handler: me.BtnEnd, bind: { hidden: "{hideBtnEnd}" }, scope: this },
            { text: '下达生产任务', handler: me.BtnStartPro, bind: { hidden: "{hideBtnEnd}" }, scope: this }

        ];
        me.callParent();
    },
    getChemInfo: function () {
        var main = this;
        if (!this.chemInfoPanel) {
            this.chemInfoPanel = Ext.create("Ext.panel.Panel", {
                title: '产品基本信息',
                height: 180,
                layout: 'border', items: [
                    {
                        border: false,
                        region: 'west',
                        width: 300,
                        reference: 'chemInfoImgPanel',
                        html: '双击编辑',
                        listeners: {
                            afterrender: function (component) {
                                component.getEl().on('click', function () {
                                    var win = Ext.create("app.prm.project.EditProduct", { title: '选择询盘化合物', hiddenNo: true });
                                    win.on("savesuccess", function (productNo, subId) {
                                        //me.form.query("hidden[name=ProductNo]")[0].setValue(productNo);
                                        main.getViewModel().set('SubId', subId);
                                        main.chemInfoPanel.initChemInfo();
                                        win.close();
                                    });
                                    win.show();
                                });
                            }
                        }
                    },
                    {
                        region: 'center',
                        border: false,
                        defaults: {
                            bodyStyle: 'padding:20px',
                            labelAlign: 'right',
                            xtype: 'displayfield'
                        },
                        bodyStyle: 'padding-top:5px;',
                        items: [
                            {
                                fieldLabel: '化学名',
                                bind: {
                                    value: '{CnName}'
                                }
                            },
                            {
                                fieldLabel: 'CAS No',
                                bind: {
                                    value: '{CAS}'
                                }
                            },
                            {
                                fieldLabel: '分子式',
                                bind: {
                                    value: '{MF}'
                                }
                            },
                            {
                                fieldLabel: '分子量',
                                bind: {
                                    value: '{MW}'
                                }
                            }
                        ]
                    }
                ],
                initChemInfo: function () {
                    console.log('给化合物信息这块赋值');
                    var view = main.getViewModel();
                    var subId = view.get('SubId');
                    if (subId) {
                        App.AjaxGet('/api/services/app/substance/GetById?id=' + subId, function (data) {
                            var json = data.result;
                            view.set('CAS', json.cas);
                            view.set('MF', json.formula);
                            view.set('MW', json.molecularWeight);
                            view.set('CnName', json.cnName);
                            view.set('IMG', json.molPngBase64);
                            var chemInfoImgPanel = main.getReferences().chemInfoImgPanel;
                            var img = view.get('IMG');
                            if (img.length > 10) {
                                showImg(chemInfoImgPanel.getId(), img, 10, 'middle');
                            }
                            else {
                                chemInfoImgPanel.update('双击编辑');
                            }
                        });
                    }
                }
            });
        }
        return this.chemInfoPanel;
    },
    getProInfo: function () {
        if (!this.proInfoPanel) {
            this.proInfoPanel = Ext.create("Ext.form.Panel", {
                title: '项目基本信息',
                layout: {
                    type: 'table',
                    columns: 3
                },
                bodyStyle: 'padding-top:10px;',
                defaults: {
                    bodyStyle: 'padding:20px',
                    labelAlign: 'right',
                    xtype: 'textfield'
                },
                items: [
                    {
                        fieldLabel: '项目流水号',
                        xtype: 'displayfield',
                        bind: { value: '{ProjectNo}' }
                    },
                     {
                         fieldLabel: '日期',
                         allowBlank: false,
                         format: 'Y-m-d',
                         xtype: 'datefield',
                         bind: { value: '{CreateOn}' }
                     },
                      {
                          fieldLabel: '项目名称',
                          allowBlank: true,
                          bind: { value: '{ProjectName}' }
                      },
                       {
                           fieldLabel: '项目类型',
                           xtype: 'combo',
                           reference: 'projectTypeCombo',
                           triggerAction: 'all',
                           lazyRender: true,
                           mode: 'local',
                           editable: false,
                           autoSelect: true,
                           allowBlank: false,
                           store: new Ext.data.JsonStore(
                           {
                               autoLoad: false,
                               proxy: {
                                   type: 'ajax',
                                   url: '/api/services/app/SystemParams/GetParams?catalog=项目类型',
                                   reader: {
                                       type: 'json',
                                       rootProperty: function (node) {
                                           return node.result || node.children;
                                       }
                                   }
                               },
                               fields: ['id', 'parameterName']
                           }),
                           valueField: 'parameterName',
                           displayField: 'parameterName'
                       }
                       ,
                        {
                            fieldLabel: '九洲代号',
                            xtype:'displayfield',
                            allowBlank: false,
                            bind: { value: '{InquiryNo}' }
                        },
                           //{
                           //    xtype: 'combo',
                           //    reference: 'InquiryNoCombo',
                           //    allowBlank: false,
                           //    fieldLabel: '九洲代号',
                           //    emptyText: '输入代号查询',
                           //    store: Ext.create("app.ux.PrmStore", { url: '/api/services/app/inquiry/GetQuiryNo', autoLoad: false }),
                           //    queryParam: 'name',
                           //    typeAhead: false,
                           //    minChars: 1,
                           //    queryMode: 'remote',
                           //    triggerAction: 'query',
                           //    displayField: 'name',
                           //    valueField: 'subId',
                           //    bind: { value: '{InquiryNo}', rawValue: '{InquiryNo}' }
                           //},


                         {
                             fieldLabel: '客户代号',
                             allowBlank: true,
                             bind: { value: '{CustomerNo}' }
                         }
                ]
            });
        }

        return this.proInfoPanel;
    },
    getBackInfo: function () {
        if (!this.backInfoPanel) {
            this.backInfoPanel = Ext.create("Ext.form.Panel", {
                title: '项目背景情况',
                items: [
                {
                    xtype: 'panel',
                    border: false,
                    layout: {
                        type: 'table',
                        columns: 3
                    },
                    bodyStyle: 'padding-top:10px;',
                    defaults: {
                        bodyStyle: 'padding:20px',
                        labelAlign: 'right',
                        xtype: 'textfield'
                    },
                    bodyStyle: 'padding-top:20px;',
                    items: [
                          {
                              xtype: 'combo',
                              reference: 'CustomerCombo',
                              name: 'PMId',
                              allowBlank: false,
                              fieldLabel: '客户名称',
                              emptyText: '输入姓名查询',
                              store: Ext.create("app.ux.PrmStore", { url: '/api/services/app/user/GetCustomers', autoLoad: false }),
                              queryParam: 'name',
                              typeAhead: false,
                              minChars: 1,
                              queryMode: 'remote',
                              triggerAction: 'query',
                              displayField: 'name',
                              valueField: 'id',
                              bind: { value: '{CustomerId}', rawValue: '{CustomerName}' }
                          },
                        {
                            fieldLabel: '产品',
                            bind: { value: '{ProductName}' }
                        },
                        {
                            fieldLabel: '规格要求',
                            xtype: 'combo',
                            reference: 'specCombo',
                            triggerAction: 'all',
                            lazyRender: true,
                            mode: 'local',
                            editable: false,
                            autoSelect: true,
                            allowBlank: false,
                            store: ['九洲开发', '客户规格'],
                            bind: { rawValue: '{spec}' }
                        },
                        {
                            fieldLabel: '工艺路线',
                            xtype: 'combo',
                            triggerAction: 'all',
                            reference: 'synthCombo',
                            lazyRender: true,
                            mode: 'local',
                            editable: false,
                            autoSelect: true,
                            allowBlank: false,
                            store: ['九洲开发', '客户工艺'],
                            bind: { rawValue: '{synth}' }
                        },
                        {
                            fieldLabel: '临床阶段',
                            xtype: 'combo',
                            reference: 'phaseCombo',
                            triggerAction: 'all',
                            lazyRender: true,
                            mode: 'local',
                            editable: false,
                            autoSelect: true,
                            allowBlank: false,
                            store: new Ext.data.JsonStore(
                            {
                                autoLoad: false,
                                proxy: {
                                    type: 'ajax',
                                    url: '/api/services/app/SystemParams/GetParams?catalog=临床阶段',
                                    reader: {
                                        type: 'json',
                                        rootProperty: function (node) {
                                            return node.result || node.children;
                                        }
                                    }
                                },
                                fields: ['id', 'parameterName']
                            }),
                            valueField: 'parameterName',
                            displayField: 'parameterName'
                        },
                        {
                            fieldLabel: '治疗领域',
                            xtype: 'combo',
                            reference: 'indicationCombo',
                            triggerAction: 'all',
                            lazyRender: true,
                            mode: 'local',
                            editable: false,
                            autoSelect: true,
                            allowBlank: false,
                            store: new Ext.data.JsonStore(
                            {
                                autoLoad: false,
                                proxy: {
                                    type: 'ajax',
                                    url: '/api/services/app/SystemParams/GetParams?catalog=治疗领域',
                                    reader: {
                                        type: 'json',
                                        rootProperty: function (node) {
                                            return node.result || node.children;
                                        }
                                    }
                                },
                                fields: ['id', 'parameterName']
                            }),
                            valueField: 'parameterName',
                            displayField: 'parameterName'
                        },
                        {
                            fieldLabel: '危险品',
                            xtype: 'checkbox',
                            checked: false,
                            reference: 'isSafeChk'
                        },
                        {
                            fieldLabel: '数量(此次询盘)',
                            bind: { value: '{NeedCurNum}' }
                        },
                        {
                            fieldLabel: '数量(未来峰值)',
                            bind: { value: '{NeedMaxNum}' }
                        },
                        {
                            fieldLabel: '用途',
                            xtype: 'combo',
                            reference: 'purposeCombo',
                            triggerAction: 'all',
                            lazyRender: true,
                            mode: 'local',
                            editable: false,
                            autoSelect: true,
                            allowBlank: false,
                            store: new Ext.data.JsonStore(
                            {
                                autoLoad: false,
                                proxy: {
                                    type: 'ajax',
                                    url: '/api/services/app/SystemParams/GetParams?catalog=项目背景化合物用途',
                                    reader: {
                                        type: 'json',
                                        rootProperty: function (node) {
                                            return node.result || node.children;
                                        }
                                    }
                                },
                                fields: ['id', 'parameterName']
                            }),
                            valueField: 'parameterName',
                            displayField: 'parameterName'
                        },
                        {
                            fieldLabel: '要求交期',
                            xtype: 'datefield',
                            allowBlank: false,
                            format: 'Y-m-d',
                            bind: { value: '{TargetDate}' }
                        },
                          {
                              xtype: 'combo',
                              reference: 'PMId',
                              name: 'PMId',
                              allowBlank: false,
                              fieldLabel: '项目经理',
                              emptyText: '输入姓名查询',
                              store: Ext.create("app.ux.PrmStore", { url: '/api/services/app/user/GetUsers', autoLoad: false }),
                              queryParam: 'name',
                              typeAhead: false,
                              minChars: 1,
                              queryMode: 'remote',
                              triggerAction: 'query',
                              displayField: 'name',
                              valueField: 'id',
                              bind: { value: '{AdminId}', rawValue: '{AdminName}' }
                          }
                    ]
                }
                ,
                Ext.create('app.ux.UploadPanel', {
                    enableFileProtect: false,
                    labelName: '背景附件',
                    reference: 'filePanel'
                }),
                Ext.create('app.ux.UploadPanel', {
                    enableFileProtect: false,
                    hiddenEdit: true,
                    labelName: '评估结果附件',
                    reference: 'tafilePanel'
                })
                ]



            });
        }
        return this.backInfoPanel;
    }
    ,
    Submit: function () {
        var me = this;
        var model = me.getViewModel();
        var refs = me.getReferences();
        var json = {};
        json["ProjectNo"] = model.get('ProjectNo');
        json["CreateOn"] = model.get('CreateOn');
        json["ProjectName"] = model.get('ProjectName');
        json["ProjectType"] = refs.projectTypeCombo.getValue();// model.get('ProjectType');
        json["InquiryNo"] = model.get('InquiryNo');
        json["CustomerNo"] = model.get('CustomerNo');

        json["SubId"] = model.get('SubId');
        json["AdminId"] = model.get('AdminId');

        json["CustomerId"] = model.get('CustomerId');
        //CustomerId

        json["CustomerName"] = model.get('CustomerName');
        json["ProductName"] = model.get('ProductName');
        json["IsDeveSpecial"] = refs.specCombo.getValue() == "九洲开发" ? true : false;
        json["IsDeveSynth"] = refs.synthCombo.getValue() == "九洲开发" ? true : false;

        json["Phase"] = refs.phaseCombo.getValue();
        json["Indication"] = refs.indicationCombo.getValue();
        json["IsSafe"] = refs.isSafeChk.checked;
        json["NeedCurNum"] = model.get('NeedCurNum');
        json["NeedMaxNum"] = model.get('NeedMaxNum');
        json["Purpose"] = refs.purposeCombo.getValue();
        json["TargetDate"] = model.get('TargetDate');
        json["Files"] = JSON.stringify(refs.filePanel.docs);

        var isValid = true;
        if (!me.getBackInfo().getForm().isValid()) {
            isValid = false;
        }
        if (!me.getProInfo().getForm().isValid()) {
            isValid = false;
        }

        if (!model.get('SubId') || model.get('SubId') == 0) {
            isValid = false;
            alert('请录入询盘化合物');
        }


        if (json["AdminId"] == '' || isNaN(json["AdminId"])) {
            isValid = false;
            alert('请通过选择录入负责人');
        }

        if (json["CustomerId"] == '' || isNaN(json["CustomerId"])) {
            isValid = false;
            alert('请通过选择录入客户');
        }
        //CustomerId

        if (isValid) {
            json["Id"] = model.get('InquiryId');
            App.AjaxPost('/api/services/app/inquiry/Create', json, function () {
                me.fireEvent("savesuccess");
            });
        }

    },
    BtnReTA: function () {
        var main = this;
        //todo:文本输入；
        var win = Ext.create("Ext.window.Window",
            {
                title: '重新评估备注项',
                width: 400,
                height: 300,
                buttonAlign: 'center',
                referenceHolder: true,
                buttons: [{
                    text: '提交', handler: function () {

                        var refs = win.getReferences();
                        var txt = refs.remarktxt.getValue();
                        win.close();
                        main.UpdateStatus(100, txt);
                    }
                }],
                layout: 'fit',
                items: [
                    {
                        reference: 'remarktxt',
                        xtype: 'textarea'
                    }
                ]
            });
        win.show();
        //this.UpdateStatus(100);
    },

    BtnPending: function () {
        this.UpdateStatus(200);
    },
    BtnEnd: function () {
        this.UpdateStatus(300);
    }, BtnStartPro: function () {
        this.UpdateStatus(400);
    },
    UpdateStatus: function (status, txt) {
        var me = this;
        var model = me.getViewModel();
        var json = {};
        {
            json["Id"] = model.get('InquiryId');
            json["status"] = status;
            json["remark"] = txt||'';
            App.AjaxPost('/api/services/app/inquiry/CommitStatu', json, function () {
                me.fireEvent("savesuccess");
            });
        }

    },
    listeners: {
        afterrender: function (win) {
            var view = win.getViewModel();
            view.set('InquiryId', win.inquiryId);
            view.set('SubId', win.subId);
            var refs = win.getReferences();

            if (win.inquiryId && win.inquiryId > 0) {
                App.AjaxGet('/api/services/app/inquiry/Get?id=' + win.inquiryId, function (json) {
                    var result = json.result;
                    view.set('CustomerId', 1);
                    view.set('AdminId', result.adminId);
                    view.set("AdminName", result.adminName);
                    view.set('CreateOn', new Date(result.createOn));
                    view.set('CustomerName', result.customerName);
                    view.set('CustomerNo', result.customerNo);
                    view.set('Files', result.files);
                    view.set('status', result.status);
                    view.set('IMG', result.img);
                    view.set('Indication', result.indication);
                    view.set('InquiryId', result.inquiryId);
                    view.set('InquiryNo', result.inquiryNo);
                    view.set('InquiryAbSubId', result.subId);

                    view.set('IsDeveSpecial', result.isDeveSpecial);
                    view.set('IsDeveSynth', result.isDeveSynth);
                    refs.isSafeChk.setValue(result.isSafe);
                    view.set('MF', result.mf);
                    view.set('MW', result.mw);
                    view.set('NeedCurNum', result.needCurNum);
                    view.set('NeedMaxNum', result.needMaxNum);
                    view.set('Phase', result.phase);
                    view.set('ProductName', result.productName);
                    view.set('ProjectName', result.projectName);
                    view.set('ProjectNo', result.projectNo);
                    view.set('ProjectType', result.projectType);
                    view.set('Purpose', result.purpose);
                    view.set('CAS', result.subCas);
                    view.set('CnName', result.subName);
                    view.set('TargetDate', new Date(result.targetDate));
                    win.loadStoreData();
                    if (result.files && result.files.length > 5) {
                        refs.filePanel.setValue(Ext.decode(result.files));
                    }
                    if (result.taFiles && result.taFiles.length > 5) {
                        refs.tafilePanel.setValue(Ext.decode(result.taFiles));
                    }
                });
            } else {
                win.loadStoreData();
                App.AjaxGet('/api/services/app/inquiry/GetInquiryProjectNo', function (json) {
                    var result = json.result;
                    view.set('ProjectNo', result);
                });
            }




            win.chemInfoPanel.initChemInfo();
        }
    },
    loadStoreData: function () {
        var win = this;
        var refs = win.getReferences();
        var view = win.getViewModel();
        var projectTypeComboStore = refs.projectTypeCombo.getStore();
        projectTypeComboStore.on('load', function () {
            refs.projectTypeCombo.setRawValue(view.get('ProjectType'));
        });
        projectTypeComboStore.load();

        var indicationComboStore = refs.indicationCombo.getStore();
        indicationComboStore.on('load', function () {
            refs.indicationCombo.setRawValue(view.get('Indication'));
        });
        indicationComboStore.load();

        var phaseComboStore = refs.phaseCombo.getStore();
        phaseComboStore.on('load', function () {
            refs.phaseCombo.setRawValue(view.get('Phase'));
        });
        phaseComboStore.load();

        var purposeComboStore = refs.purposeCombo.getStore();
        purposeComboStore.on('load', function () {
            refs.purposeCombo.setRawValue(view.get('Purpose'));
        });
        purposeComboStore.load();
    }

})